package com.gopay.scheduler.job;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.datasource.DBType;
import com.gopay.common.datasource.DbContextHolder;
import com.gopay.common.domain.report.Event;
import com.gopay.common.domain.report.MqEventTimeoutLog;
import com.gopay.common.report.dao.MqEventInfoDAO;
import com.gopay.common.report.dao.MqEventTimeoutLogDAO;
import com.gopay.scheduler.GopayBaseJob;

/**
 * 事件处理任务
 * 
 * @EventsHandlerJob.java
 * @author zhaoxubing
 * @2015年5月29日 下午4:35:08 www.gopay.com.cn Inc.All rights reserved.
 */
public class EventTimoutLogJob extends GopayBaseJob {
    // 日志
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
    private static final int TOTAL_EVENT_COUNT=480;

    @Resource(name="mqEventInfoDAO")
    private MqEventInfoDAO mqEventInfoDAO;

    @Resource(name="mqEventTimeoutLogDAO")
    private MqEventTimeoutLogDAO mqEventTimeoutLogDAO;

    public void doJobInternal() {
       
        List<MqEventTimeoutLog> timoutLogList = this.queryTimeoutLog();
        List<Event> saveEventList = new ArrayList<Event>();
        for (MqEventTimeoutLog m : timoutLogList) {
            Event e = new Event();
            e.setBatchTaskId(m.getBatchTaskId());
            e.setCreatedTs(m.getCreatedTs());
            e.setGopayOrderId(m.getGopayOrderId());
            e.setLastUpdTs(m.getLastUpdTs());
            e.setRemark1(m.getRemark1());
            e.setRemark2(m.getRemark2());
            e.setSnapshot(m.getSnapshot());
            e.setStat("01");
            e.setType(m.getType());
            e.setVersion(0);
            saveEventList.add(e);
            m.setStat("02");
        }
        
        logger.info("timoutLogList.size=" + timoutLogList.size());
        DbContextHolder.setDbType(DBType.DS_REPORT.value);
        mqEventInfoDAO.saveOrUpdateAll(saveEventList);
        mqEventTimeoutLogDAO.saveOrUpdateAll(timoutLogList);
       
    }
    
    private List<MqEventTimeoutLog> queryTimeoutLog() {
//        DbContextHolder.setDbType(DBType.DS_ONLY_READ.value);
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DAY_OF_YEAR, -7);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("stat", "01");
        String queryHql = "FROM MqEventTimeoutLog m WHERE m.stat = :stat order by m.createdTs desc";
        
        return mqEventTimeoutLogDAO.findByHql(queryHql, map,1,TOTAL_EVENT_COUNT);
        
    }
    
}
